package my.mark.mybaibaoxiang.eventDemo.nhr;

import lombok.extern.slf4j.Slf4j;
import my.mark.mybaibaoxiang.eventDemo.tests.TestDomain;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wxming.
 * @date 2025/8/7.
 * @Description NHR异步事件发送消息实践，事件执行的方法也是每个事件独立的。
 */

@Service
@Slf4j
public class Test implements ApplicationEventPublisherAware {

    @Transactional(rollbackFor = Exception.class)
    public void mytest() {
        //各个事件并没有线程隔离，线程不安全。如果往里面传入对象，值是会变的，所以for循环里每个都需要new。
        for (int i=0;i<100;i++) {
            //人可能很多，异步发送
            TestDomain domain = new TestDomain("name", i+"", "sex");
            applicationEventPublisher.publishEvent(PmMessageEvent.of(domain,PmMessageTemplateEnum.PM_CONTRACT_REMIND_TO_OBJ_EMP.getMsg(), ()->{
                System.out.println("emp"+ domain.getAge());
            }));
        }
    }

    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
